package apptoko.com;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.event.Event.ClientUpdateNameNotFoundEvent;
import apptoko.com.event.Event.LatestVersionEvent;
import apptoko.com.model.AppStoreVnAboutUpdateData;
import apptoko.com.model.ApptokoUpdateData;
import apptoko.com.network.DownloadUpdateTask;
import apptoko.com.network.IDownloadUpdateCallback;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;

import apptoko.com.R;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

public class AboutActivity extends Activity implements android.view.View.OnClickListener,IDownloadUpdateCallback{

	private static final int REQUEST_CODE = 99;
	private Button btnCheckUpdate;
	private TextView version;
	private ProgressDialog progressLoading;
	private String updateUri;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_about);
		EasyTracker.getInstance().setContext(this);
		btnCheckUpdate = (Button) findViewById(R.id.btn_okay);
		version = (TextView) findViewById(R.id.about_version);
//		TextView twitter=(TextView)findViewById(R.id.twitteracc);
//		twitter.setOnClickListener(new View.OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/apptoko"));
//				startActivity(intent);
//			}
//		});
		btnCheckUpdate.setOnClickListener(this);
		progressLoading=new ProgressDialog(this);
		progressLoading.setMessage(getResources().getString(R.string.checking_update));
		progressLoading.setCancelable(true);
		try {
			PackageInfo ai = getPackageManager().getPackageInfo("apptoko.com", 0);
			version.setText(getResources().getString(R.string.version) + ": " + ai.versionName+" build "+ai.versionCode);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(requestCode == REQUEST_CODE && resultCode == RESULT_OK){
			if(updateUri.startsWith("market")){
				try {
				    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(updateUri)));
				} catch (android.content.ActivityNotFoundException anfe) {
				}
			}else{
				DownloadUpdateTask task = new DownloadUpdateTask(this);
				task.setDownloadCallback(this);
				task.execute(updateUri);
			}
		}
	}
	
	@Override
	public void onClick(View v) {
		checkForUpdate();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		com.facebook.AppEventsLogger.activateApp(this, getResources().getString(R.string.fb_app_id));
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
		EventBus.getDefault().unregister(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
		EventBus.getDefault().unregister(this);
		EventBus.getDefault().register(this);
	}

	@Override
	public void onDownloadComplete(String path) {
		Utils.installAPK(this, path);
		finish();
	}

	@Override
	public void onDownloadError() {
		AlertDialog.Builder builder=new Builder(this);
		builder.setMessage(R.string.couldntdownloadnewversion).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		}).create().show();
	}
	
	private void checkForUpdate(){
		Log.e("checkForUpdate","cfu");
		String deviceStatus;
		apptoko.com.util.RootUtil root = new apptoko.com.util.RootUtil();
		boolean isRooted = root.isDeviceRooted();
		((AppStoreVnApplication)getApplication()).setRooted(isRooted);
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putBoolean(Constants.IS_ROOTED, isRooted).commit();
		if(isRooted){
			deviceStatus = "1";
		} else {
			deviceStatus = "0";
		}
		progressLoading.show();
		BackgroundTasks bgTask=new BackgroundTasks(this);
		bgTask.checkClientUpdate(deviceStatus,true);
	}
	
	public void onEventMainThread(ClientUpdateNameNotFoundEvent event){
		if(progressLoading!=null && progressLoading.isShowing()){
			progressLoading.dismiss();
		}
	}
	
	public void onEventMainThread(LatestVersionEvent event){
		Log.e("latest","latest");
//		Toast.makeText(this, getResources().getString(R.string.updated_latest), Toast.LENGTH_LONG).show();
		if(progressLoading!=null && progressLoading.isShowing()){
			progressLoading.dismiss();
		}
	}
	public void onEventMainThread(AppStoreVnAboutUpdateData data){
		if(progressLoading!=null && progressLoading.isShowing()){
			progressLoading.dismiss();
		}
		
		updateUri = data.getUpdateUrl();
		if(updateUri.startsWith("market")){
			if(data.isForce()){
				try {
				    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(updateUri)));
				    finish();
				} catch (android.content.ActivityNotFoundException anfe) {
				}
			} else {
				Intent showUpdate = new Intent(this, PopupUpdateActivity.class);
				Bundle bundle = new Bundle();
				bundle.putBoolean("fromAbout", true);
				bundle.putSerializable(HomeActivity.KEY_UPDATE_DATA, data);
				showUpdate.putExtras(bundle);
				startActivityForResult(showUpdate, REQUEST_CODE);
			}
		} else {
			if(data.isForce()){
					DownloadUpdateTask task = new DownloadUpdateTask(this);
					task.setDownloadCallback(this);
					task.execute(updateUri);
			} else {
				Intent showUpdate = new Intent(this, PopupUpdateActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable(HomeActivity.KEY_UPDATE_DATA, data);
				bundle.putBoolean("fromAbout", true);
				showUpdate.putExtras(bundle);
				startActivityForResult(showUpdate, REQUEST_CODE);
			}
		}
		
	}
}
